package yunjiao.designpatterns.singleton;

import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * TODO
 *
 * @author yangyunjiao
 */
public class SingletonClass {
    private static final String CONNECTION_FILE_WITH_PATH = "dbconnection.properties";
    private static volatile SingletonClass SINGLE_INSTANCE = null;

    private final Properties properties = new Properties();

    private SingletonClass() {}

    public static SingletonClass getInstance() throws IOException {
        if (SINGLE_INSTANCE == null) {
            synchronized (SingletonClass.class) {
                if (SINGLE_INSTANCE == null) {
                    ClassPathResource resource = new ClassPathResource(CONNECTION_FILE_WITH_PATH);
                    SINGLE_INSTANCE = new SingletonClass();
                    SINGLE_INSTANCE.properties.load(resource.getInputStream());
                }
            }
        }
        return SINGLE_INSTANCE;
    }

    public String getPropertyValue(String propertyKey) {
        if (propertyKey != null && !propertyKey.isEmpty()) {
            return properties.getProperty(propertyKey);
        }
        return null;
    }

    public Map<String, String> getProperties() {
        Map<String, String> propertyMap = new HashMap<String, String>();
        for (String propertyKey : properties.stringPropertyNames()) {
            propertyMap.put(propertyKey, properties.getProperty(propertyKey));
        }
        return propertyMap;
    }
}
